package com.qlm.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.qlm.cache.MsgCache;
import com.qlm.entity.Order;
import com.qlm.entity.User;
import com.qlm.entity.Yhq;
import com.qlm.service.UserService;
import com.qlm.service.impl.UserServiceImpl;
import com.qlm.tool.Delivery;
import com.qlm.tool.WxUtil;

public class MyMsgController extends MsgControllerAdapter{
	private static final Logger logger = LoggerFactory.getLogger(MyMsgController.class);

	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appid"));
		ac.setAppSecret(PropKit.get("appsecret"));

		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey",
				"setting it in config file"));
		return ac;
	}

	@Override
	protected void processInFollowEvent(InFollowEvent arg0) {
		if (InFollowEvent.EVENT_INFOLLOW_SUBSCRIBE.equals(arg0.getEvent()))
		{
			String openid = arg0.getFromUserName();
			User user = User.dao.findById(openid);
			int isGet = 0;
			if(user != null){
				isGet = WxUtil.getInt("attentionget", user,0);
				if(isGet != 1){//未发送优惠券
					user.set("attentionget", 1).update();
					sendYhq(openid,2);
				}
			}else{
				ApiResult result = null ;
				try {
					result = UserApi.getUserInfo(openid);
				} catch (Exception e) {
					logger.info("拉取用户信息失败"+openid);
				}				
				if(result != null){
					UserService s = new UserServiceImpl();
					user = s.getUserInfoFromWXAndSave(openid, result);
					user.set("attentionget", 1).update();
					sendYhq(openid,2);
				}				
			}
			OutTextMsg outMsg = new OutTextMsg(arg0);
			StringBuilder msg = new StringBuilder();
			msg.append("终于等到您！/:,@-D/:,@-D/:,@-D/::*/::*/::*\n").append("欢迎关注果然FruitC公众号。/::D/::D/::D\n")
			.append("果然商城全新上线，您身边的水果超市！点击菜单即可进入哦/:hug/:hug/:hug\n");
			if(isGet != 1){
				msg.append("首次关注果然FruitC公众号获得").append("30元优惠券奖励,请进入果然商城查看，满100元即可使用哦/::B/::B/::B\n");									
			}
			outMsg.setContent(msg.toString());
			render(outMsg);
		}
		// 如果为取消关注事件，将无法接收到传回的信息
		if (InFollowEvent.EVENT_INFOLLOW_UNSUBSCRIBE.equals(arg0.getEvent()))
		{
			logger.info("取消关注：" + arg0.getFromUserName());
		}

		
	}
	public static void sendYhq(String openid,int type){
		int yhmoney = 10,tmoney = 50;
		String desc = "满50元减10元";
		if(type == 2){
			yhmoney = 30;tmoney = 100;
			desc = "满100元减30元";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date parse = new Date();
		try {
			parse = sdf.parse("2017-11-26");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Yhq yhq = new Yhq();
		yhq.set("yhmoney_", yhmoney).set("tmoney_", tmoney).set("dead_time_", parse).set("openid_", openid).set("status_", 0)
		.set("desc_", desc).set("create_time_", new Date()).set("type_", 1).save();
		logger.info("添加优惠券openid:"+openid+",描述:"+desc);
	}

	@Override
	protected void processInTextMsg(InTextMsg inTextMsg) {
		String msg = inTextMsg.getContent();
		String returnMsg = "欢迎来到果然FruitC，/:,@-D/:,@-D/:,@-D有什么建议可以在公众号留言哦。/:,@f/:,@f/:,@f";
		if(msg != null){
			String returnMsg1 = MsgCache.getMsg(msg);
			if(returnMsg1 != null){
				returnMsg = returnMsg1;
			}
		}
		OutTextMsg outMsg = new OutTextMsg(inTextMsg);
		outMsg.setContent(returnMsg);
		render(outMsg);
	}

	@Override
	protected void processInMenuEvent(InMenuEvent inMenuEvent) {
		OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
		String eventKey = inMenuEvent.getEventKey();
		String openid = inMenuEvent.getFromUserName();
		StringBuilder msg = new StringBuilder();
		if("querydelivery".equals(eventKey)){//查询快递
			queryDelivery(openid, msg);
		}else if("getYhq".equals(eventKey)){
			sendAttentionYhq(openid,msg);
		}
		outMsg.setContent(msg.toString());
		render(outMsg);
	}

	private void sendAttentionYhq(String openid, StringBuilder msg) {
		User user = User.dao.findById(openid);
		int isGet = 0;
		if(user != null){
			isGet = WxUtil.getInt("attentionget", user,0);
			if(isGet != 1){//未发送优惠券
				user.set("attentionget", 1).update();
				sendYhq(openid,2);
			}
		}else{
			ApiResult result = null ;
			try {
				result = UserApi.getUserInfo(openid);
			} catch (Exception e) {
				logger.info("拉取用户信息失败"+openid);
			}				
			if(result != null){
				UserService s = new UserServiceImpl();
				user = s.getUserInfoFromWXAndSave(openid, result);
				user.set("attentionget", 1).update();
				sendYhq(openid,2);
			}	
		}
		if(isGet != 1){
			msg.append("30元优惠券已经发放到您的账户中啦，请点击菜单进入果然商城查看，满100元即可使用哦/::B/::B/::B\n");
		}else{
			msg.append("您已经领取过该优惠券啦./:,@-D/:,@-D/:,@-D\n");
		}
		msg.append("快让朋友们关注公众号领取优惠券哦/:,@f/:,@f/:,@f");
	}

	private void queryDelivery(String openid, StringBuilder msg) {
		List<Order> find = Order.dao.find("select logistics_number_ num_ from t_order where openid_ = '"+openid+"' and status_ = 4");
		if(find.isEmpty()){
			msg.append("暂时没有查询到您的物流信息哦，快去果然商城下单哦");
		}else{
			for (Order order : find) {
				String str = order.getStr("num_");
				Delivery query = Delivery.query(str);
				if(query.isSuccess()){
					msg.append("物流名称：百世汇通\n物流单号:"+str+" \n最新物流信息如下：\n");
					Delivery[] data = query.getData();
					msg.append("时间："+data[0].getTime()+","+data[0].getContext()+"\n");
				}else{
					msg.append("物流单号:"+str+" 暂时没有查到物流信息.\n");
				}
			}	
		}
	}


}
